﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Zavand.Web.Mvc.Manana.SampleWebsite.Common
{
    public class MockStorage:IStorage
    {
        private static List<User> _users = new List<User>();

        public List<User> GetAllUsers()
        {
            return _users
                .Select(UserConvertor.Clone)
                .ToList();
        }

        public List<User> GetUsers(int page, int pageSize, out int total)
        {
            total = _users.Count;
            return _users
                .Skip((page-1)*pageSize)
                .Take(pageSize)
                .Select(UserConvertor.Clone)
                .ToList();
        }

        public void InsertUser(User u)
        {
            var o = _users.FirstOrDefault(m => m.ID == u.ID);
            if (o != null)
                throw new Exception("User already exists");
            _users.Add(UserConvertor.Clone(u));
        }

        public void UpdateUser(User u)
        {
            var o = _users.FirstOrDefault(m => m.ID == u.ID);
            if (o != null)
                throw new Exception("User doesn't exist");
            UserConvertor.Update(o, u);
        }

        public void DeleteUser(User u)
        {
            var o = _users.FirstOrDefault(m => m.ID == u.ID);
            if (o != null)
                throw new Exception("User doesn't exist");
            _users.Remove(o);
        }

        public void Init()
        {
            var r = new Random((int) DateTime.Now.Ticks);
            for (int i = 0; i < 100; i++)
            {
                _users.Add(new User
                               {
                                   ID = i + 1,
                                   FirstName = String.Format("FirstName {0:#,0}", i + 1),
                                   LastName = String.Format("LastName {0:#,0}", i + 1),
                                   Birthday = new DateTime(r.Next(1920,2000),r.Next(1,13),r.Next(1,29))
                               });
            }
        }
    }
}